package com.klhappy.houyuan.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.klhappy.houyuan.R;
import com.klhappy.houyuan.bean.BaseJsonBean;
import com.klhappy.houyuan.bean.RegisterBean;
import com.klhappy.houyuan.bean.RegisterResponseBean;
import com.klhappy.houyuan.constant.KeyConstant;
import com.klhappy.houyuan.constant.UrlConstant;
import com.klhappy.houyuan.interfaces.CallBackInterModle;
import com.klhappy.houyuan.modle.GetPassWordModle;
import com.klhappy.houyuan.utils.GsonRequest;
import com.klhappy.houyuan.utils.JsonCode;
import com.klhappy.houyuan.view.AbsActivity;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import java.util.HashMap;

//注册界面
public class RegisterActivity extends AbsActivity implements CallBackInterModle {

    boolean refreshReg = false;
    private int count = 60;
    private Handler handlerBtn = new Handler();
    private GetPassWordModle modle;
    private String mCookie;
    private RegisterResponseBean responseBean;

    private GsonRequest<RegisterBean> mRequest = null;

    @InjectView(R.id.edit_zhanghao)
    EditText etAccount;
    @InjectView(R.id.edit_mima)
    EditText etPassword;
    @InjectView(R.id.edit_tuijian)
    EditText edit_tuijian;
    @InjectView(R.id.edit_yanzhengma)
    EditText etRegistCode;
    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.button_yanzhengma)
    Button sendCodeBtn;

    @OnClick(R.id.click_ra)
    public void click_ra() {
        finish();
    }

    @OnClick(R.id.button_yanzhengma)
    public void yanzhengma() {
        if (count == 60) {
            String userPhone = etAccount.getText().toString();
            String telRegex = "[1][0-9]\\d{9}";
            if (userPhone.length() != 11 && !userPhone.matches(telRegex)) {
                Toast.makeText(getApplicationContext(), "请正确输入手机号",
                        Toast.LENGTH_LONG).show();
            } else {
                sendCodeBtn.setClickable(false);
                sendCodeBtn.setBackgroundResource(R.drawable.corner_bg3);
                sendCodeBtn.setTextColor(0xffffffff);
                {
                    refreshReg = false;
                    regist(userPhone);
                }
            }
        }
    }

    @OnClick(R.id.btn_regist)
    public void regist() {
        String account = etAccount.getText().toString();
        String password = etPassword.getText().toString();
        String registCode = etRegistCode.getText().toString();
        String tuijianma = edit_tuijian.getText().toString();
        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(registCode)) {
            showDialog("注册中...");
            modle.setAccount(account, password, registCode, tuijianma);
        } else {
            showToast("请正确输入");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        ButterKnife.inject(this);
        title.setText(R.string.register_houyuan);
        modle = new GetPassWordModle(this);
        modle.setCallBackInterModle(this);
    }


    @Override
    public void CallBackFromModle(String url, BaseJsonBean o) {
        if (url.equals(UrlConstant.REGIST_URL)) {
            if (o.getCode() == 200) {
                responseBean = JsonCode.getClass(o.getEntity() ,RegisterResponseBean.class);
                mConfigManage.set(KeyConstant.account, etAccount.getText().toString());
                mConfigManage.set(KeyConstant.password, etPassword.getText().toString());
                if (!TextUtils.isEmpty(mConfigManage.get(KeyConstant.session, ""))) {
                    mConfigManage.remove(KeyConstant.session);
                }
                mConfigManage.set(KeyConstant.session, responseBean.getInv_code());
                RegisterActivity.this.startActivity(new Intent(RegisterActivity.this, Houyuan_MainActivity.class));
                RegisterActivity.this.finish();
            } else {
                showToastx(o.getMsg());
            }
            closeDialog();
        }
    }

    private void regist(String account) {
        mConfigManage.remove(KeyConstant.cookie);
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", account);
        Listener<RegisterBean> listener = new Listener<RegisterBean>() {
            @Override
            public void onResponse(RegisterBean response) {
                Gson gson = new Gson();
                Log.e("pu", gson.toJson(response));
                if (response.code == 200){
                    showToastx("验证码发送成功,请稍等...");
                    handler.post(runnable);
                    mConfigManage.set(KeyConstant.cookie ,mCookie);
                }
            }
        };
        ErrorListener errorListener = new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                showToast("网路错误");
            }
        };
        mRequest = new GsonRequest<RegisterBean>(Request.Method.POST, UrlConstant.PWD_URL, map,
                RegisterBean.class, listener, errorListener) {
            @Override
            protected Response<RegisterBean> parseNetworkResponse(NetworkResponse response) {
                mCookie = getCookie(response);
                mConfigManage.remove(KeyConstant.cookie);
                return super.parseNetworkResponse(response);
            }
        };

        getAppEnv().getVolleyRequest().add(mRequest);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private Runnable runnable = new Runnable() {

        @Override
        public void run() {
            if (count > 0) {
                if (refreshReg) {
                    refresh();
                    return;
                }
                count--;
                sendCodeBtn.setText(count + "秒后重发");
                handlerBtn.postDelayed(runnable, 1000);
            } else if (count == 0) {
                refresh();
                return;
            }
        }
    };

    private void refresh() {
        count = 60;
        sendCodeBtn.setText("发送验证码");
        sendCodeBtn.setClickable(true);
        sendCodeBtn.setTextColor(Color.WHITE);
        sendCodeBtn.setBackgroundResource(R.drawable.corner_bg2);
        handlerBtn.removeCallbacks(runnable);
        return;
    }
}
